package edu.gdut.thesissys.service;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import edu.gdut.thesissys.action.director.UpdateTeacherAction;
import edu.gdut.thesissys.dao.DaoFactory;
import edu.gdut.thesissys.dao.IHQLQuery;
import edu.gdut.thesissys.vo.Major;
import edu.gdut.thesissys.vo.Teacher;

/**
 * 增删改查Teacher
 * 
 * @author gauze
 * 
 */
public class TeacherService {
	private static final Logger log = LoggerFactory
			.getLogger(TeacherService.class);
	@Resource(name = "daoFactory")
	private DaoFactory daoFactory;
	@Autowired
	private IHQLQuery hqlQuery;

	/**
	 * 删除Teacher
	 * 
	 * @param teacherId
	 *            教师工号
	 * @return
	 */
	@Transactional
	public Boolean deleteTeacher(String teacherId) {
		Boolean result = new Boolean(false);
		log.debug("delete teacher by id " + teacherId);
		try {
			daoFactory.getBaseDAO(Teacher.class).delete(
					daoFactory.getBaseDAO(Teacher.class).findById(teacherId));// 删除
			result = true;
		} catch (Exception e) {
			log.error("delete teacher by id " + teacherId
					+ " failed and return false", e);
			return new Boolean(false);
		}
		log.debug("delete teacher by id " + teacherId
				+ " successful and return " + result);
		return result;
	}

	/**
	 * 保存或更新teacher
	 * 
	 * @param action
	 * @return
	 */
	@Transactional
	public Boolean saveOrUpdateTeahcer(UpdateTeacherAction action) {
		Boolean result = new Boolean(false);
		log.debug("save or update teacher");
		try {
			Teacher teacher;
			if (action.getTeacherId()
					.equalsIgnoreCase(action.getNewTeacherId())) {
				teacher = daoFactory.getBaseDAO(Teacher.class).findById(
						action.getTeacherId());// 已存在对象
			} else {
				teacher = new Teacher();
				teacher.setTeacherId(action.getNewTeacherId());// 新对象
			}
			// 注入信息
			teacher.setDuty(action.getDuty());
			teacher.setEmail(action.getEmail());
			teacher.setName(action.getName());
			teacher.setLimitNum(action.getLimitNum());
			teacher.setMajor(daoFactory.getBaseDAO(Major.class).findById(
					action.getMajorId()));
			teacher.setPassword(action.getPassword());
			teacher.setPhone(action.getPhone());
			teacher.setPowerRight(action.getPowerRight());
			teacher.setSex(action.getSex());

			daoFactory.getBaseDAO(Teacher.class).attachDirty(teacher);// 保存或者更新
			result = true;
		} catch (Exception e) {
			log.error("save or update teacher failed and return false", e);
			return new Boolean(false);
		}
		log.debug("save or uddate teahcer successful and return " + result);
		return result;
	}

	/**
	 * teacher bean转换成json
	 * 
	 * @param teacher
	 *            teacher bean instance
	 * @return
	 */
	public JSONObject toTeacherJson(Teacher teacher) {
		JSONObject teacherJson = new JSONObject();
		log.debug("translate teacher bean to json");
		try {
			// 输出teacher信息到json
			teacherJson.accumulate("id", teacher.getTeacherId());
			JSONObject majorJson = new JSONObject();
			JSONObject departmentJson = new JSONObject();
			majorJson.accumulate("id", teacher.getMajor().getMajorId());
			majorJson.accumulate("name", teacher.getMajor().getName());
			departmentJson.accumulate("id", teacher.getDepartment()
					.getDepartmentId());
			departmentJson
					.accumulate("name", teacher.getDepartment().getName());
			teacherJson.accumulate("major", majorJson);
			teacherJson.accumulate("department", departmentJson);
			teacherJson.accumulate("name", teacher.getName());
			teacherJson.accumulate("sex", teacher.getSex());
			teacherJson.accumulate("duty", teacher.getDuty());
			teacherJson.accumulate("workUnit", teacher.getWorkUnit());
			teacherJson.accumulate("phone", teacher.getPhone());
			teacherJson.accumulate("powerRight", teacher.getPowerRight());
			teacherJson.accumulate("limitNum", teacher.getLimitNum());
			teacherJson.accumulate("email", teacher.getEmail());
		} catch (Exception e) {
			log.error("translate failed and return new json with none", e);
			return new JSONObject();
		}
		log.debug("translate successful and return " + teacherJson.toString());
		return teacherJson;
	}

	/**
	 * 查找teacher
	 * 
	 * @param teacherId
	 *            教师工号
	 * @return
	 */
	@Transactional(readOnly = true)
	public JSONObject findTeacherJson(String teacherId) {
		JSONObject teacherJson = new JSONObject();
		log.debug("find teacher by id " + teacherId);
		try {
			Teacher teacher = daoFactory.getBaseDAO(Teacher.class).findById(
					teacherId);// 查找teacher
			teacherJson = toTeacherJson(teacher);// 输出teacher信息到json
		} catch (Exception e) {
			log.error("find teacher by id " + teacherId
					+ " failed and return new json with none", e);
			return new JSONObject();
		}
		log.debug("find teacher successful and return "
				+ teacherJson.toString());
		return teacherJson;
	}

	/**
	 * 查找教师
	 * 
	 * @param offset
	 *            开始位置
	 * @param pagesize
	 *            查询总记录数
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public JSONArray findTeachersJson(int offset, int pagesize) {
		JSONArray teachersArray = new JSONArray();
		log.debug("find all teacher");
		try {
			String hql = "from Teacher as teacher order by teacher.department.departmentId,teacher.major.majorId";
			List teachersList = hqlQuery.find(hql, offset, pagesize);// 查找教师
			for (Object teacher : teachersList) {
				if (teacher instanceof Teacher) {
					teachersArray.add(toTeacherJson((Teacher) teacher));// 添加教师json信息
				}
			}
		} catch (Exception e) {
			log.error("find all teacher failed and return new json with none",
					e);
			return new JSONArray();
		}
		log.debug("find all teacher successful");
		return teachersArray;
	}

}
